<?php

namespace app\api\controller;

use think\exception\ValidateException;
use think\facade\Log;
use Throwable;
use ba\Captcha;
use ba\ClickCaptcha;
use think\facade\Config;
use app\common\facade\Token;
use app\common\controller\Frontend;
use app\api\validate\User as UserValidate;
use think\facade\Db;
use EasyWeChat\OfficialAccount\Application;

class User extends Frontend
{
    protected array $noNeedLogin = ['checkIn', 'logout', 'wechatLogin'];

    protected array $noNeedPermission = ['*'];

    protected object $wechat;

    public function initialize (): void
    {
        parent::initialize();
        $pay = Config::get("easy_wechat");
        $this->wechat = new Application($pay);
    }

    /**
     * 公众号微信授权登录
     */
    public function wechatLogin (): void
    {


        $params = $this->request->param();
        if (empty($params['code'])) {
            $this->error("缺少参数");
        }
//        try {
//            $oauth = $this->wechat->getOAuth();
//            Log::info('微信code' . json_encode($params['code']));
//
//            $weinfo = $oauth->userFromCode($params['code']);
//            Log::info('微信成功' . json_encode($weinfo));
//
//        } catch (\Exception $e) {
//            Log::error('微信失败' . $e->getMessage());
//        }

        // halt(json_decode(json_encode($weinfo),true));
        $user = new \app\admin\model\User;
        $find = $user
            ->where(['open_id' => 'o4ft_6IMSNXTIDvyPZU7kXxgMYzM' ])
//            ->where(['open_id' => $weinfo->getId() ])
            ->find();
//        if (empty($find)) {
//            // 没有则注册
//            $user->username = \ba\Random::uuid();
//            $user->nickname = $weinfo->getNickname();
//            $user->avatar = $weinfo->getAvatar();
//            $user->status = 'enable';
//            $user->open_id = $weinfo->getId();
//            $user->save();
//            $find = $user;
//            // halt($find);
//
//            event('couponGifts', [
//                'user_id' => $user->id,
//                'gifts'   => 'register'
//            ]);
//        } else {
//            // 有则登录
//            #更新用户信息
//            $find->nickname = $weinfo->getNickname();
//            $find->avatar = $weinfo->getAvatar();
//            $find->save();
//        }
        $this->auth->direct($find->id);
        $this->success(__('Login succeeded!'), $this->auth->getUserInfo());

    }

    /**
     * 会员签入(登录和注册)
     * @throws Throwable
     */
    public function checkIn (): void
    {
        $openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }

        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'type' => $this->auth::LOGGED_IN
            ], $this->auth::LOGIN_RESPONSE_CODE);
        }

        if ($this->request->isPost()) {
            $params = $this->request->post(['tab', 'email', 'mobile', 'username', 'password', 'keep', 'captcha', 'captchaId', 'captchaInfo', 'registerType']);
            if (!in_array($params['tab'], ['login', 'register'])) {
                $this->error(__('Unknown operation'));
            }

            $validate = new UserValidate();
            try {
                $validate->scene($params['tab'])->check($params);
            } catch (Throwable $e) {
                $this->error($e->getMessage());
            }

            if ($params['tab'] == 'login') {
                $captchaObj = new ClickCaptcha();
                if (!$captchaObj->check($params['captchaId'], $params['captchaInfo'])) {
                    $this->error(__('Captcha error'));
                }
                $res = $this->auth->login($params['username'], $params['password'], (bool)$params['keep']);
            } elseif ($params['tab'] == 'register') {
                $captchaObj = new Captcha();
                if (!$captchaObj->check($params['captcha'], ($params['registerType'] == 'email' ? $params['email'] : $params['mobile']) . 'user_register')) {
                    $this->error(__('Please enter the correct verification code'));
                }
                $res = $this->auth->register($params['username'], $params['password'], $params['mobile'], $params['email']);
            }

            if (isset($res) && $res === true) {
                $this->success(__('Login succeeded!'), [
                    'userInfo'  => $this->auth->getUserInfo(),
                    'routePath' => '/user'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Check in failed, please try again or contact the website administrator~');
                $this->error($msg);
            }
        }

        $this->success('', [
            'accountVerificationType' => get_account_verification_type()
        ]);
    }

    public function logout (): void
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refreshToken', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success();
        }
    }

    /**
     * 获取用户的余额
     */
    public function money (): void
    {
        $this->success('', $this->auth->getUserInfo());
    }

    /**
     * 是否有支付密码
     * @return void
     */
    public function isPayPassword (): void
    {
        $user = \app\admin\model\User::find($this->auth->id);

        $this->success('', ['isPayPassword' => (bool)$user->pay_password]);
    }

    /**
     * 修改支付密码
     * @return void
     */
    public function setPayPassword (): void
    {
        $pay_password = $this->request->param('pay_password');
        $old_pay_password = $this->request->param('old_pay_password');

        $user = \app\admin\model\User::find($this->auth->id);

        #为空则设置
        if (!empty($user->pay_password) && $user->pay_password != $old_pay_password) {
            $this->error('原支付密码错误');
        }
        if (empty($pay_password)) {
            $this->error('新支付密码不能为空');
        }
        $user->pay_password = $pay_password;
        $user->save();

        $this->success('修改成功');
    }

    /**
     * 找回密码
     * @return void
     */
    public function findPayPassword (): void
    {
        $post = $this->request->post();

        $tel = $post['tel'];
        $code = $post['code'];
        $template_code = $post['template_code'];
        $pay_password = $this->request->param('pay_password');

        if (empty($tel) || empty($code) || empty($template_code) || empty($pay_password)) {
            $this->error('参数不能为空');
        }

        #验证短信验证码是否正确
        try {
            sms_check($tel, $code, $template_code);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $user = \app\admin\model\User::find($this->auth->id);
        $user->pay_password = $pay_password;
        $user->save();

        $this->success('修改成功');
    }

}